// @/utils/websocket.js
import {
	isJSON
} from "@/webscoket/json"
import siteInfo from '../siteinfo.js'
import api from '@/api/index.js'
import $store from "@/store/index.js"
class WebSocketClass {
	constructor(id) {
		this.lockReconnect = false; // 是否开始重连
		this.wsUrl = siteInfo.webSocketUrl + '?id=' + id; // ws 地址
		this.globalCallback = null; // 回调方法
		this.userClose = false; // 是否主动关闭

		this.createWebSocket();
	}

	createWebSocket() {
		var self = this
		this.ws = uni.connectSocket({
			url: this.wsUrl,
			success(data) {
				self.initEventHandle();
			},
		});
	}
	callbackFunction(res) {
		if (res.type == 'bind') {
			var resz = api.live['bindClient']({
				'client_id': res.client_id
			})
		} else {
			uni.$emit('WsMessage', res)
		}
	}

	// 初始化
	initEventHandle() {
		var that = this
		uni.onSocketOpen(function(res) {
			setInterval(function() {
				uni.sendSocketMessage({
					data: JSON.stringify({
						type: 'ping'
					})
				})
			}, 10000)
		});


		uni.onSocketClose(function(res) {
			if (!that.userClose) {
				that.reconnect(that.wsUrl); //重连
			}
		})

		uni.onSocketError(function(res) {
			if (!that.userClose) {
				that.reconnect(that.wsUrl); //重连
			}
		})
		uni.onSocketMessage(function(event) {
			if (isJSON(event.data)) {
				const jsonobject = JSON.parse(event.data)
				that.callbackFunction(jsonobject)
			} else {
				that.callbackFunction(event.data)
			}
		})



	}

	// 关闭ws连接回调
	reconnect(url) {
		if (this.lockReconnect) return;
		this.lockReconnect = true; // 关闭重连，没连接上会一直重连，设置延迟避免请求过多
		setTimeout(() => {
			this.createWebSocket(url);
			this.lockReconnect = false;
		}, 1000);
	}



	// 获取ws返回的数据方法
	getWebSocketMsg(callback) {
		this.globalCallback = callback
	}

	// 关闭ws方法
	closeSocket() {
		if (this.ws) {
			this.userClose = true;
			$store.commit('wsNum', 0)
			$store.commit('ws', false)

			this.ws.close({
				success(res) {
					console.log("关闭成功", res)
				},
				fail(err) {
					console.log("关闭失败", err)
				}
			});
		}
	}

	writeToScreen(massage) {
		console.log(massage);
	}
}
export default WebSocketClass;